<template>
  <CommonPage>
    <MyTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="customerApi.list"
      :index="true"
      :query-format="queryFormat"
      list-key="customer_list"
    >
      <template #search>
        <MyTQI>
          <n-input
            v-model:value="queryItems.searchVal"
            type="text"
            placeholder="请输入客户名称"
            clearable
          >
            <template #suffix>
              <n-icon size="20" :component="Search"></n-icon>
            </template>
          </n-input>
        </MyTQI>
        <MyTQI>
          <n-input
            v-model:value="queryItems.contactorName"
            type="text"
            placeholder="请输入对接人"
            clearable
          >
            <template #suffix>
              <n-icon size="20" :component="Search"></n-icon>
            </template>
          </n-input>
        </MyTQI>
        <MyTQI label="接入时间" :content-width="300">
          <n-date-picker
            v-model:formatted-value="queryItems.timeRange"
            type="daterange"
            clearable
          />
        </MyTQI>
      </template>
      <template #action>
        <n-button v-permission="`customer_add`" type="primary" @click="handleAdd">
          添加客户
        </n-button>
      </template>
    </MyTable>
    <MyModal
      ref="$form"
      :model-form="model"
      :disabled="type === 'view'"
      :width="900"
      @submit="handleSubmit"
    >
      <n-form-item
        label="客户名称"
        path="name"
        :rule="{ required: true, message: '请输入客户名称' }"
      >
        <n-input v-model:value="model.name" maxlength="50" show-count clearable />
      </n-form-item>
      <n-form-item
        label="对接人"
        path="contactorDtoList"
        :rule="[
          { required: true, type: 'array', min: 1, message: '请添加对接人' },
          {
            validator: (rule, value, callback) =>
              validatorContactor(rule, value, callback, 'CUSTOMER_FLAG_ADD'),
          },
        ]"
      >
        <Contacter v-model="model.contactorDtoList" :disabled="type === 'view'" />
      </n-form-item>
      <n-form-item label="接入时间" path="abutmentTime">
        <n-date-picker
          v-model:formatted-value="model.abutmentTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          :time-picker-props="{ format: 'HH:mm' }"
          type="datetime"
          placeholder="选择时间"
          clearable
        />
      </n-form-item>
      <n-form-item label="备注" path="remark">
        <n-input
          v-model:value="model.remark"
          clearable
          :maxlength="300"
          show-count
          type="textarea"
          :autosize="{
            minRows: 3,
          }"
        />
      </n-form-item>
    </MyModal>
  </CommonPage>
</template>

<script setup lang="jsx">
import { useUserStore } from '@/store'
import { Search } from '@vicons/ionicons5'
import * as customerApi from '@/api/customer'
import { useCrudPro } from '@/hooks/useCrudPro'
defineOptions({ name: 'CustomerIndex' })
function queryFormat({ timeRange, ...params }) {
  if (timeRange?.length === 2) {
    const [startTime, endTime] = timeRange
    params.startTime = startTime
    params.endTime = endTime
  }
  return params
}
const queryItems = ref({})
const userStore = useUserStore()
function encryption(phone) {
  if (phone) {
    if (userStore.isHigh) {
      return phone
    } else {
      let ary = phone.split('')
      ary.splice(3, 4, '****')
      return ary.join('')
    }
  } else {
    return null
  }
}
const columns = [
  {
    title: '客户名称',
    key: 'name',
  },
  {
    title: '对接人',
    key: 'contactorDtoList',
    render({ contactorDtoList = [] }) {
      return (
        <div style="white-space: pre-wrap">
          {contactorDtoList
            .map(
              (item) =>
                `${item.contactorName}-${encryption(item.contactorPhone) || '暂无'}-${
                  item.remark || '暂无'
                }\n`
            )
            .join('')}
        </div>
      )
    },
  },
  {
    title: '对接时间',
    key: 'abutmentTime',
    render: ({ abutmentTime }) => $format(abutmentTime),
  },
  {
    title: '客户备注',
    key: 'remark',
  },
  {
    title: '操作',
    key: 'actions',
    width: 220,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          {/* <n-button v-permission="customer_view" text onClick={() => handleView(row)}>
            查看
          </n-button> */}
          <n-button v-permission="customer_update" text onClick={() => handleEdit(row)}>
            修改
          </n-button>
          <n-button
            v-permission="customer_delete"
            text
            onClick={() =>
              handleDelete(
                { id: row.id },
                {
                  title: '删除客户',
                  content: `请确定是否删除客户：${row.name}`,
                }
              )
            }
          >
            删除
          </n-button>
        </n-flex>
      )
    },
  },
]
function validatorContactor(_, val, callback, flag) {
  if (Array.isArray(val)) {
    const map = {
      CUSTOMER_FLAG_CHOOSE: 'id',
      CUSTOMER_FLAG_ADD: 'contactorName',
    }
    const exist = val.filter((item) => item[map[flag]] && item.status !== 'DELETED')
    const norepeat = [...new Set(exist.map((item) => item[map[flag]]))]
    if (norepeat.length !== exist.length) {
      callback(new Error('存在重复对接人'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
const {
  type,
  model,
  $form,
  $table,
  handleAdd,
  handleEdit,
  handleSubmit,
  handleDelete,
  // handleView,
} = useCrudPro({
  name: '客户',
  initForm: {
    id: null,
    name: null,
    contactorDtoList: [],
    abutmentTime: null,
    remark: null,
  },
  apis: {
    add: customerApi.add,
    edit: customerApi.edit,
    del: customerApi.del,
    info: ({ id }) => customerApi.info({ id }).then((res) => res.data),
  },
})
</script>
